import React from 'react';
import styles from './index.less';
import { Modal, Button } from 'antd';
import { Input } from 'antd';
import { Row } from 'antd';

const { TextArea } = Input;

export default class WebChat extends React.Component {
  private socket: WebSocket | undefined;
  private outputArea: HTMLDivElement | null | undefined;
  public state = {
    loading: false,
    visible: false,
    input: '',
    msgContain: [],
  };

  componentDidMount() {
    this.socket = new WebSocket('ws://localhost:8001');
    this.socket.onopen = () => {
      this.socket?.send('1234');
      console.log('hello world');
    };
    this.socket.onmessage = this.onHandleMessage;
  }

  componentWillUnmount() {
    this.socket && this.socket.close();
  }

  onHandleMessage(msg: any) {
    console.log(msg);
    const { type, data } = JSON.parse(msg);
    switch (type) {
      case 'message':
        this.setState({ msgContain: [...this.state.msgContain, data] }, this.scrollToBottom);
        break;
    }
  }

  showModal = () => {
    this.setState({ visible: true });
  };

  hideModal = () => {
    this.setState({ visible: false });
  };

  onChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    this.setState({ input: event.target.value });
  };

  scrollToBottom = () => {
    if (this.outputArea) {
      const scrollHeight = this.outputArea.scrollHeight;
      const height = this.outputArea.clientHeight;
      const maxScrollTop = scrollHeight - height;
      this.outputArea.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
    }
  };

  sendMessage = () => {
    this.setState(
      { input: '', msgContain: [...this.state.msgContain, this.state.input] },
      this.scrollToBottom,
    );
  };

  render() {
    return (
      <>
        <div className={styles.WebChat} id="webChat" onClick={this.showModal}>
          <span className={styles.logo}>💬</span>
        </div>
        <Modal
          className={styles.modal}
          visible={this.state.visible}
          title="聊天室"
          onCancel={this.hideModal}
          footer={null}
          width="80%"
        >
          <div
            className={styles.outputArea}
            ref={(el) => {
              this.outputArea = el;
            }}
          >
            {this.state.msgContain.map((msg) => (
              <p>{msg}</p>
            ))}
          </div>
          <TextArea
            className={styles.inputArea}
            value={this.state.input}
            onChange={this.onChange}
          />
          <Row justify="end">
            <Button key="submit" type="primary" onClick={this.sendMessage}>
              发送
            </Button>
          </Row>
        </Modal>
      </>
    );
  }
}
